package com.adee.java.jdbc.pooled;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidDatasource {
    private  static DataSource ds = null;
    static {
        Properties props = new Properties();
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
        try {
            props.load(is);
            ds = DruidDataSourceFactory.createDataSource(props);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException, SQLException {
        Connection conn1 = ds.getConnection();
        String sql = "SELECT * FROM admin";
        //conn1.close();

        Connection conn2 = ds.getConnection();
        //conn2.close();

        Connection conn3 = ds.getConnection();

        Connection conn4 = ds.getConnection();

        Connection conn5 = ds.getConnection();

        Connection conn6 = ds.getConnection();

        Connection conn7 = ds.getConnection();

        Connection conn8 = ds.getConnection();


    }

    //得到连接对象
    public  static Connection getConnection(){
        Connection connection = null;
        try {
            connection = ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //归还连接对象到连接池中
    public static  void close(Connection connection){
        if(connection!=null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
    }
}
